package cn.xerllent.wxtp.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;

import cn.hutool.core.util.ObjectUtil;
import cn.xerllent.common.entity.vo.OffsetPageable;
import cn.xerllent.common.service.impl.BaseServiceImpl;
import cn.xerllent.wxtp.entity.WxCorp;
import cn.xerllent.wxtp.entity.WxReport;
import cn.xerllent.wxtp.service.WxCorpService;
import cn.xerllent.wxtp.service.WxReportService;
import cn.xerllent.wxtp.service.mapper.WxReportMapper;
import me.chanjar.weixin.common.api.WxConsts.MediaFileType;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpTpIdTranslate;
import me.chanjar.weixin.cp.bean.WxCpTpIdTranslateResp;
import me.chanjar.weixin.cp.bean.WxCpTpIdTranslateResultResp;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

//@Service
//@AllArgsConstructor
//@CacheConfig(cacheNames = "user")
//@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public abstract class WxReportServiceImpl extends BaseServiceImpl<WxReportMapper, WxReport>  implements WxReportService {

    @Value("${file.public}")
    private String pubpath;

	@Value("${file.files:}")
    private String files;
	
	@Resource
	private WxCorpService wxCorpService;
	
	@Override
	public String getReportPath() {
		if(ObjectUtil.isEmpty(files)) {
			return pubpath+(pubpath.endsWith(File.separator)?"":File.separator)+"files"+File.separator+"report";
		}
		return files+(files.endsWith(File.separator)?"":File.separator)+"report";
	}
	
    @Override
    //@Cacheable
    public List<WxReport> queryAll(WxReport filter, OffsetPageable offsetPageable) {
    	PageMethod.offsetPage(offsetPageable.getOffset(), offsetPageable.getPageSize(), false);//false 表示不需要count查询
        PageInfo<WxReport> page = new PageInfo<>(queryAll(filter));
        return page.getList();
    }

    @Override
    public List<WxReport> queryAll(WxReport filter) {
    	//方法1
    	QueryWrapper<WxReport> querywrapper = new QueryWrapper<>();
    	if(ObjectUtil.isNotEmpty(filter)) {
        	if(ObjectUtil.isNotEmpty(filter.getCorpId())) {
        		querywrapper.eq("corp_id", filter.getCorpId());
        	}
        	if(ObjectUtil.isNotEmpty(filter.getSuiteId())) {
        		querywrapper.eq("suite_id", filter.getSuiteId());
        	}
        	if(ObjectUtil.isNotEmpty(filter.getUserid())) {
        		querywrapper.eq("user_id", filter.getUserid());
        	}
        	if(ObjectUtil.isNotEmpty(filter.getType())) {
        		querywrapper.eq("type", filter.getType());
        	}
        	if(filter.getStatus()!=null) {
        		querywrapper.eq("status", filter.getStatus());
        	}
        	querywrapper.orderByDesc("id");
    	}
    	return baseMapper.selectList(querywrapper);
    }

    
	/**
	 * 上传转译文件
	 *  2上传媒体
	 *  3执行id转译
	 *  4等待回调
	 * */
	@Override
	public void doIdTranslate(final WxReport resource, final WxCpTpService tpService) {
    	//2上传媒体
        try {
			String filePath = getReportPath() +File.separator + resource.getFilepath();
			File file = new File(filePath);
//          下面注释的代码,accesstoken获取方法可以参考！！不删
//			WxCorp wxCorp = wxCorpService.getOne(new LambdaUpdateWrapper<WxCorp>().eq(WxCorp::getCorpId, resource.getCorpId()).eq(WxCorp::getSuiteId, resource.getSuiteId()));
//			//初始化authcorp accesstoken，一次调用后缓存到redis，今后在子WxCpTpMediaService，WxCpTpContactService里看是否可以调用
//			tpService.getCorpToken(wxCorp.getCorpId(), wxCorp.getPermanentCode(),false);
//			WxMediaUploadResult  result = tpService.getWxCpTpMediaService().upload(MediaFileType.FILE, file, resource.getCorpId());
			
			//不能用上面方法，apiurl地址不对，必须用下面自己添加的方法
			WxMediaUploadResult  result = tpService.getWxCpTpContactService().upload(MediaFileType.FILE, file);
			resource.setMediaId(result.getMediaId()).setStatus(2);
        	saveOrUpdate(resource);
		} catch (Exception e) {
			saveOrUpdate(resource.setStatus(-2));
			return;
		}
		
    	//3提交转译
        try {
			List<String> mediaIdList = new ArrayList<String>();
			mediaIdList.add(resource.getMediaId());
			WxCpTpIdTranslate wxCpTpIdTranslate = new WxCpTpIdTranslate()
					.setAuthCorpId(resource.getCorpId())
					.setMediaIdList(mediaIdList);
			WxCpTpIdTranslateResp result = tpService.getWxCpTpContactService().idTranslate(wxCpTpIdTranslate);
			resource.setJobid(result.getJobId()).setStatus(3);
			saveOrUpdate(resource);
		} catch (Exception e) {
			saveOrUpdate(resource.setStatus(-3));
			return;
		}
        
    	//4等待转译回调=BatchJobHandler,下面代码无用了
//        TimerTask timerTask = new TimerTask() {
//            @Override
//            public void run() {
//            	try {
//					WxCpTpIdTranslateResultResp  result = tpService.getWxCpTpContactService().getBatchResult(resource.getJobid());
//					if(resource.getStatus()<4) {  //没有回调返回时
//						resource.setUrl(result.getResult().getContactIdTranslate().getUrl()).setStatus(4);
//						saveOrUpdate(resource);
//					}
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//            }
//        };
//        // 在指定延迟2分钟后开始，
//        new Timer().schedule(timerTask,2*60*1000L);

	}

}
